package com.atung.merchant.service;

import com.atung.merchant.dto.AuthUserEntity;
import com.atung.merchant.enums.RoleType;
import com.atung.merchant.mapper.BusMerchantUserMapper;
import com.atung.merchant.po.BusMerchantUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class AuthSecurityService implements UserDetailsService {
    @Autowired
    private BusMerchantUserMapper busMerchantUserMapper;

    @Override
    public AuthUserEntity loadUserByUsername(String userId) throws UsernameNotFoundException {

        BusMerchantUser busMerchantUser = busMerchantUserMapper.selectById(Long.valueOf(userId));
        AuthUserEntity authUserEntity = new AuthUserEntity();
        BeanUtils.copyProperties(busMerchantUser, authUserEntity);
        List<GrantedAuthority> authorities = loadAuthoritiesForUser(busMerchantUser);
        authUserEntity.setAuthorities(authorities);
        return authUserEntity;
    }
    private List<GrantedAuthority> loadAuthoritiesForUser(BusMerchantUser user) {
        // Assuming there is a method to get roles from the database
        List<String> roles = new ArrayList<>();
        roles.add(user.getType() == 0 ? RoleType.MASTER.name() : RoleType.USER.name());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
        }
        return authorities;
    }
}
